import socket
import binascii
import datetime as dt
import asyncio
import time
import os
from setting import DB, socet_setting
import Mysql

def connect():
    try:
        # HOST = "192.168.0.104"
        # PORT = 5003
        # bit = 1024
        bit = socet_setting['bit']
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((socet_setting['HOST'], socet_setting['PORT']))
        sock.listen(10)
        os.system('clear')
        while True:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(start(sock, bit))
    except Exception as e:
        time_second = 10
        while range(time_second):
            time_second = time_second -1
            print(f"\033[37m\033[44mНеудачная попытка подключения. Повторная попытка через {time_second} секунд.\nОшибка : {e}\033[0m")
            time.sleep(1)
            os.system('clear')
        connect()


def send(conn, ms):
    conn.send(ms)



async def trecer_status(terminal_ID) -> dict: return await Mysql.select({'imei': terminal_ID}, '1', 'treker', DB)


async def ppp(data, addr, conn):
    start_bit = (data[0:4])
    Packet_length = (data[4:6])
    soket_id = addr[1]

    if start_bit == "7979" and Packet_length == "00":
        sokett = await Mysql.select({'soket_id': soket_id}, '1', 'treker', DB)
        imei = sokett['imei']
        print(f"\033[31m\033[47mТрекер не получает ГЕО данных IMEI - {imei} !!!\033[0m")


    # print('\033[33m Обрабатываем и сортируем \033[0m')
    print(f'\033[34m {data} прилетело с РРР \033[0m')
    protocol = (data[6:8])


    if protocol == "01":
        terminal_ID = (data[8:24])
        print(f"\033[32m {terminal_ID}\033[0m")
        a = await trecer_status(terminal_ID)
        if a == {}:
            await Mysql.create({'imei': terminal_ID, "name": 'Не назначен', 'date' : dt.datetime.now()}, 'treker', DB)
        else:
            await Mysql.insert({'soket_id': soket_id, 'date' : dt.datetime.now()}, {'imei': terminal_ID }, '1', 'treker', DB)
            # print("Повторное рукопожатие")
            pass


    elif protocol == "22":
        latitude = (data[22:30])
        longitude = (data[30:38])
        speed = (data[38:40])
        latitude = (int(latitude, 16))
        longitude = (int(longitude, 16))
        speed = (int(speed, 16))
        latitude = (latitude / 30000) / 60
        longitude = (longitude / 30000) / 60
        latitude = float('{:.6f}'.format(latitude))
        longitude = float('{:.6f}'.format(longitude))
        print(f"\033[30m\033[47m N {latitude}")
        print(f" E {longitude}")
        print(f' Speed км/ч {speed}\033[0m')
        geo_link = f"https://yandex.ru/maps/?pt={longitude},{latitude}&z=18&l=map"
        sokett = await Mysql.select({'soket_id' : soket_id}, '1', 'treker', DB)
        imei = sokett['imei']
        print(f"{imei} посмотреть что тут")
        await Mysql.create(
            {'imei': imei, 'Latitude': longitude, 'Longitude': latitude, 'date': dt.datetime.now(),
             'speed': speed, 'geo_link' : geo_link}, 'activity', DB)

    elif protocol == "13":
        start_bit=(data[0:4])
        Packet_length=(data[4:6])
        protocol=(data[6:8])
        terminal_INFO=(data[8:10])
        Voltage_level=(data[10:12])
        Voltage_level=(int(Voltage_level,16))
        GSM_Signal=(data[12:14])
        laguage=(data[14:18])
        serialNO=(data[18:22])
        err=(data[22:26])
        stop_bit=(data[26:30])
        sokett = await Mysql.select({'soket_id': soket_id}, '1', 'treker', DB)
        id = sokett['id']
        if GSM_Signal == '04':
            gsm = '100%'
        if GSM_Signal == '03':
            gsm = '75%'
        if GSM_Signal == '02':
            gsm = '50%'
        if GSM_Signal == '01':
            gsm = '25%'
        if GSM_Signal == '00':
            gsm = '0%'
        await Mysql.insert({'gsm': gsm}, {'id': id}, '1', 'treker', DB)
        # print('_______________________________')
        # print('start_bit               |',start_bit)
        # print('Packet_length           |',Packet_length)
        # print('protocol                |',protocol)
        # print('terminal_INFO           |',terminal_INFO)
        # print('Voltage_level           |',Voltage_level)
        # print('GSM_Signal              |',GSM_Signal)
        # print('laguage                 |',laguage)
        # print('serialNO                |',serialNO)
        # print('err                     |',err)
        # print('stop_bit                |',stop_bit)
        # print('_______________________________')
    else:
        pass


async def start(sock, bit):
    print('\033[32m Oжидание подключения \033[0m')
    conn, addr = sock.accept()
    try:
        conn.settimeout(10)
        print('Подключение', addr)
        data = conn.recv(bit)
        data = binascii.hexlify(data)
        data = data.decode('utf-8')
        await ppp(data, addr, conn)
        imei = (data[8:24])
        ms = ('787805010001d9dc0d0a')
        ms = binascii.unhexlify(ms)
        send(conn, ms)
        data = conn.recv(bit)
        data = binascii.hexlify(data)
        data = data.decode('utf-8')
        await ppp(data, addr, conn)
        data = conn.recv(bit)
        data = binascii.hexlify(data)
        data = data.decode('utf-8')
        await ppp(data, addr, conn)
        ms = ('787805120011f9700d0a')
        ms = binascii.unhexlify(ms)
        send(conn, ms)
        data = conn.recv(bit)
        data = binascii.hexlify(data)
        data = data.decode('utf-8')
        await ppp(data, addr, conn)
        data = conn.recv(bit)
        data = binascii.hexlify(data)
        data = data.decode('utf-8')
        await ppp(data, addr, conn)
        # print ("\033[31m ********** Закрываю соеденение!!! ********** \033[0m")
        # # sock.close()
        # # time.sleep(3)
        await Mysql.insert({'status': '✅'}, {'imei': imei}, '1', 'treker', DB)
        conn.close()
    except socket.timeout:
        try:
            trec = await Mysql.select({'imei' : imei}, '1', 'treker', DB)
            await Mysql.insert({'status': '❌'}, {'imei' : imei}, '1', 'treker', DB)
            print(" ")
            print(f"\033[31m\033[47mТрекер {trec['name']} не в сети или имеет слабый сигнал IMEI - {imei} !!!\033[0m")
            print(" ")
            print("\033[31m ********** Закрываю соеденение по таймауту!!! ********** \033[0m")
            print(" ")
            # sock.close()
            # time.sleep(3)
        except:
            print("Прилетело что то левое!!!")
        conn.close()

async def soket_close():
    pass

if __name__ == "__main__":
    connect()
        # loop.close()

# sudo kill -9 $(sudo lsof -t -i:5002)
